/**
 * 迭代器
 */

//es6的for循环迭代

class ItES6{
    constructor(){
        this.data = [1,2,3,4,5,6,7,9]
        this.index = 0
    }

    [Symbol.iterator](){
        return{
            next:()=>{
                let done = true
                if(this.index<this.data.length){
                    done = false
                }
                return {
                    value: this.data[this.index++],
                    done
                }
            }
        }
    }
}

// const it6 = new ItES6()
// for(let it of it6){
//     console.log(it)
// }

//!自定义迭代器
function myIt(data){
    let index = 0
    const len = data.length
    const it = {
        next:()=>{
            let done = true
            if(index<len) done = false
            return{
                value:data[index++],
                done
            }
        }
    }
    //利用闭包，隐藏了index，但却可以使用index的值
    return it
}

// const it = myIt([1,3,3,4,5,6,6,7])
// let res = it.next()
// while(!res.done){
//     console.log(res.value)
//     res = it.next()   
// }

//生成器函数
function* generator(data){
    let index = 0
    const len = data.length
    while(index<len){
        yield data[index++]
    }
}


const it = generator([1,3,3,4,5,6,6,7])
console.log(it[Symbol.iterator]==generator)
// let res = it.next()
// while(!res.done){
//     console.log(res.value)
//     res = it.next()   
// }

class Five{
    constructor(data){
        this.data = data
    }
    *[Symbol.iterator](){
        // for(let i=0;i<this.data.length;i++){
        //     yield this.data[i]
        // }
        yield* this.data
    }

}

const f = new Five([1,222222,34566,66])

// for(let it of f){
//     console.log(it)
// }

console.log(...f)

